import ala from 'ala'

// 初始化
export async function init () {
  var para = {
    type: ala.urlType()
  }
  var viewModel = await ala.httpGet('api/RelationTree/GetAdminTree', para)
  if (viewModel) {
    var tag = viewModel.title.replace('分类', '')
    var title = viewModel.title
    viewModel.intro = `1、您可以通过${title}来灵活的管理或区分${tag},${title}支持三级分类<br/>`
    viewModel.intro += `2、点击右上角新增按钮来新增一级${title},在表格操作一栏中可新增子${title}和删除${title},内容修改时会自动保存.您也可以点击底部保存按钮来保存<br/>`
    viewModel.intro += `3、${title}名称不能重复。拖动可排序（有子分类的一级分类不能拖动到二级分类中），拖动保存生效`
  }
  if (!viewModel.data) {
    viewModel.data = []
  }
  return viewModel
}

// 弹窗保存有操作
export function afterSave (array, model, isAdd = false) {
  if (isAdd === true) {
    return this.afterAdd(array, model)
  } else {
    return this.afterEdit(array, model)
  }
}

// 弹窗后添加操作
export function afterAdd (array, model) {
  model.children = []
  model.isEnable = model.status === 1
  if (model.fatherId === 0) {
    model.level = 1
    array.unshift(model)
  } else {
    array.forEach(one => {
      if (one.id === model.fatherId) {
        if (!one.children) {
          one.children = []
        }
        model.level = 2
        one.children.unshift(model)
      } else {
        if (one.children) {
          one.children.forEach(two => {
            if (two.id === model.fatherId) {
              if (!two.children) {
                two.children = []
              }
              model.level = 3
              two.children.unshift(model)
            }
          })
        }
      }
    })
  }
  return array
}

// 弹窗保存操作
export function afterEdit (array, model) {
  array.forEach(one => {
    if (model.fatherId === 0) {
      if (one.id === model.id) {
        one = setItem(one, model)
        one.level = 1
      }
    } else {
      if (one.children) {
        one.children.forEach(two => {
          if (two.id === model.id) {
            two = setItem(two, model)
            two.level = 2
          } else {
            if (two.children) {
              two.children.forEach(three => {
                if (three.id === model.id) {
                  three = setItem(three, model)
                  three.level = 3
                }
              })
            }
          }
        })
      }
    }
  })
  return array
}

function setItem (old, newModel) {
  old.icon = newModel.icon
  old.name = newModel.name
  old.isEnable = newModel.status === 1
  return old
}